package com.keyware.utils.keycloud;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class LicenseUtil {
	
	
	/**
	 * 获取验证
	 * 
	 * @return true：合法使用 false证明过期
	 * @return 返回 指定名称 所对应的提示信息文本
	 * @throws Throwable
	 * @throws SAXException
	 * @throws ParserConfigurationException
	 */
	public Json getVerification(HttpServletRequest request, String loginName) throws Exception, SAXException, IOException {
		Json messageInfo = new Json();;
		String XMLPath = request.getSession().getServletContext().getRealPath("resources")+File.separator+"keycloud"+File.separator+"license"+File.separator+"LicenseVrify.xml";
	    String signPath =request.getSession().getServletContext().getRealPath("resources")+File.separator+"keycloud"+File.separator+"license"+File.separator+"License.xml";
		/*String XMLPath ="../LicenseVrify.xml";
		String signPath="../License.xml";*/
		/*KeyGenerater  keyGenerater = new KeyGenerater();
		keyGenerater.generater();*/
		String strPubKey ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDG/iiVm3jIytrXOJXs0vfaKTq8V0VlfGk4+cVWn9mRzTM7+JbYF/Cmz8pXsa1B360M8VOmr0GYaPRljgmCow5cFrQEV1fkZbn22Js46AP9mWn6HhbDkgc7Njamlk+8TqNBbXN++Thsb9VnqwF7MLqxaPfN+9ADWjo202bTFhq6bQIDAQAB";
		/*System.out.println(strPubKey);*/
		boolean verify = LicenseVerify.Verify(XMLPath, signPath, strPubKey);
		if (!verify) {
			messageInfo.setMsg("授权验证失败，请联系开发商！");
			messageInfo.setSuccess(false);
			return messageInfo;
		}
		String parameters = licenseVerify(XMLPath);
		String[] param = parameters.split(",");
		if (!"unlimited".equals(param[0])) {
			// 验证授权开始时间
			int createDateFlag = dateVerify(param[2]);
			if (createDateFlag == 1) {
				messageInfo.setMsg("当前时间早于授权开始时间，请联系开发商！");
				messageInfo.setSuccess(false);
				return messageInfo;
			}
			// 验证结束时间
			int dateFlag = dateVerify(param[0]);
			if (dateFlag == -1) {
				messageInfo.setMsg("授权过期，请联系开发商！");
				messageInfo.setSuccess(false);
				return messageInfo;
			}

		}
		// 验证MAC地址
		/*int macFalg = macVerify(param[3]);
		if (macFalg == -1) {
			messageInfo.setMsg("主机MAC地址异常，请联系开发商！");
			messageInfo.setSuccess(false);
			return messageInfo;
		}*/
		OnlineUser onlineUser = new OnlineUser();
		onlineUser.setsId(request.getSession().getId());
		// onlineUser.setId(request.getSession().getUserId(request.getSession()));
		onlineUser.setName(loginName);
		int count = Integer.parseInt(param[1]);// 获取设定人数
		request.getSession().setAttribute(SessionListener.LISTENER_MAX_USER_COUNT, count);
		String tf = (String) request.getSession().getAttribute("continueTF");
		request.getSession().removeAttribute("continueTF");
		if ("F".equals(tf)) {
			String ipnow = getMACAddress().substring(0, getMACAddress().length() - 4);
			messageInfo.setMsg("当前使用人数已满!");
			messageInfo.setSuccess(false);
			return messageInfo;
		}
		request.getSession().setAttribute(SessionListener.LISTENER_NAME, onlineUser);
		// 添加对Ip地址的License验证 张怀珠 20140412
		if (param.length > 4) {
			int SystemPart = systemPart(param[4]);
			if (SystemPart == 1) {
				messageInfo.setMsg("服务器IP地址变动，验证失败!");
				messageInfo.setSuccess(false);
				return messageInfo;
			}
		}
		// 添加对计算机名的验证 张怀珠 20140421
		if (param.length > 5) {
			int localhost = localhostVerify(param[5]);
			if (localhost == -1) {
				messageInfo.setMsg("计算机名验证失败!");
				messageInfo.setSuccess(false);
				return messageInfo;
			}
		}
		messageInfo.setSuccess(true);
		return messageInfo;
	}

	/**
	 * 
	 * 解析License文件
	 * 
	 * @param path
	 * @return 解析后的参数集合
	 * @author 张怀珠
	 * @date 2015-11-11
	 */
	public String licenseVerify(String path) throws ParserConfigurationException, SAXException, IOException {
		// 解析xml文档// 创建解析工厂指定DocumentBuilder
		DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document document = db.parse(new File(path));// 把文件解析成DOCUMENT类型
		Element root = document.getDocumentElement();
		// 子节点
		String paramters = "";
		NodeList childList = root.getChildNodes();
		for (int x = 0; x < childList.getLength(); x++) {
			Node childNode = childList.item(x);
			// 判断取出的值是否属于Element元素,目的是过滤掉
			if (childNode instanceof Element) {
				// 验证使用时间
				if (childNode.getNodeName().equals("SubscriptionExpiry")) {
					paramters += childNode.getNodeValue() + ",";
				}
				// 验证部署的主机mac码
				/*if (childNode.getNodeName().equals("SerialNumber")) {
					paramters += childNode.getTextContent() + ",";
				}*/
				// 验证在线人数
				if (childNode.getNodeName().equals("LimitedUsers")) {
					paramters += childNode.getNodeValue() + ",";
				}
				// 验证创建时间
				if (childNode.getNodeName().equals("CreateDate")) {
					paramters += childNode.getNodeValue() + ",";
				}
			}
		}

		return paramters;
	}

	/**
	 * 
	 * 验证使用日期
	 * 
	 * @param 解析所得的日期字符串
	 * @return 过期返回-1，未过期返回1。
	 * @author 张怀珠
	 * @date 2015-11-11
	 */
	public int dateVerify(String textContent) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		// 获取的xml里的时间跟系统时间进行比较
		String nowDate = formatter.format(date);
		ParsePosition parse = new ParsePosition(0);
		ParsePosition parseOne = new ParsePosition(0);
		Date dateOne = formatter.parse(textContent, parse);
		Date dateTwo = formatter.parse(nowDate, parseOne);
		long longg = dateOne.getTime() - dateTwo.getTime();
		System.out.println(textContent);
		System.out.println(dateOne);

		if (longg < 1) {
			return -1;
		} else {
			return 1;
		}
	}

	/**
	 * 
	 * 验证mac地址
	 * 
	 * @param macString
	 * @return mac地址相同返回1，不同返回-1；
	 * @author 张怀珠
	 * @date 2015-11-11
	 */
	public int macVerify(String macString) {
		int flag = -1;
		String javaMAC = getMacAddress();
		String[] macArray = javaMAC.split(",");
		for (int i = 0; i < macArray.length; i++) {
			if (macString.equals(macArray[i])) {
				flag = 1;
				break;
			}
		}
		return flag;
	}

	/**
	 * 
	 * 获取本地mac地址
	 * 
	 * @return 本地mac地址字符串
	 * @author 张怀珠
	 * @date 2015-11-11
	 */
	public String getMacAddress() {
		String address = "";
		String os = "";
		os = System.getProperty("os.name");
		if (os.startsWith("Windows")) {
			try {
				String command = "cmd.exe /c ipconfig /all";// /C:/Users/Administrator>ipconfig/all
				Process p = Runtime.getRuntime().exec(command);
				BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
				String line;
				while ((line = br.readLine()) != null) {
					if (line.indexOf("物理地址") > 0 || line.indexOf("physical address") > 0 || line.indexOf("Physical Address") > 0) {
						int index = line.indexOf(":");
						index += 2;
						address += line.substring(index) + ",";
					}
				}
				br.close();
				return address.trim();
			} catch (IOException e) {
			}
		} else if (os.startsWith("Linux")) {
			String command = "/bin/sh -c ifconfig -a";
			Process p;
			try {
				p = Runtime.getRuntime().exec(command);
				BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
				String line;
				while ((line = br.readLine()) != null) {
					if (line.indexOf("HWaddr") > 0) {
						int index = line.indexOf("HWaddr") + "HWaddr".length();
						address += line.substring(index) + ",";
					}
				}
				br.close();
			} catch (IOException e) {
			}
		}
		address = address.trim();
		return address;

	}

	/**
	 * 
	 * 获取服务器端ip地址
	 * 
	 * @return 服务器端ip地址字符串
	 * @author 张怀珠
	 * @date 2015-11-12
	 */
	public String getMACAddress() {
		String address = "";
		String os = System.getProperty("os.name");
		if (os != null && os.startsWith("Windows")) {
			try {
				String command = "cmd.exe /c ipconfig /all";
				Process p = Runtime.getRuntime().exec(command);
				BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
				String line;
				while ((line = br.readLine()) != null) {
					if (line.indexOf("IPv4 地址") > 0 || line.indexOf("IP Address") > 0) {
						int index = line.indexOf(":");
						index += 2;
						address = line.substring(index);
						break;
					}
				}
				br.close();
				return address.trim();
			} catch (IOException e) {
			}
		}
		return address;
	}

	/**
	 * 
	 * 添加对ip地址的license验证
	 * 
	 * @return ip的匹配标识
	 * @author 张怀珠
	 * @date 2015-11-12
	 */
	public int systemPart(String SystemPart) {
		String address = getMACAddress().trim();
		if (address.contains("(首选)")) {
			address = address.substring(0, address.length() - 4);
		}
		if (SystemPart.equals(address.trim())) {
			return -1;
		}
		return 1;
	}

	/**
	 * 
	 * 验证计算机名
	 * 
	 * @param 解析所得的计算机名
	 * @return 计算机名不一致返回-1,计算机名一致返回1。
	 * @author 张怀珠
	 * @date 2015-11-12
	 */
	public int localhostVerify(String localhost) {
		InetAddress addr = null;
		String address = "";
		try {
			addr = InetAddress.getLocalHost();
			address = addr.getHostName().toString();// 获得本机名称
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (address.equals(localhost)) {
			return 1;
		}
		return -1;
	}
	
}
